<?php

namespace App\Transformers;

use App\Models\User;
use League\Fractal\TransformerAbstract;
use Illuminate\Support\Str;

class UserTransformer extends TransformerAbstract
{
    protected $availableIncludes = ['collects', 'setting'];
    public function transform(User $user)
    {
        return [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'introduction' => (string) $user->introduction,
            'avatar' => Str::startsWith($user->avatar, 'http') ? $user->avatar : (!empty($user->avatar) ? 'https://pic.touxiangge.com/' . $user->avatar . '/w144' : null),
            'created_at' => (string) $user->created_at,
            'updated_at' => (string) $user->updated_at,
            'collect_count' => $user->collects_count ?: 0,
            'followers_count' => $user->followers_count ?: 0,
            'followings_count' => $user->followings_count ?: 0,
            'movies_count' => $user->movies_count ?: 0,
            'setting' => $this->initSetting($user),
            'unread_notifications_count' => $user->notification_count
        ];
    }

    public function includeCollects(User $user)
    {
        return $this->collection($user->collects, new CollectTransformer());
    }

    public function includeSetting(User $user)
    {
        return $this->array($user->setting);
    }

    public function initSetting(User $user)
    {
        if (! $user->setting) {
            $user->setting()->create(['user_id' => $user->id]);
            return $user->setting()->first();
        }
        return $user->setting;
    }
}
